package com.laolang.thresh.module.system.user.business;

import com.laolang.thresh.framework.common.util.web.ServletUtil;
import com.laolang.thresh.module.system.user.consts.SysUserLoginLogEnums.OpSource;
import com.laolang.thresh.module.system.user.consts.SysUserLoginLogEnums.OpType;
import com.laolang.thresh.module.system.user.entity.SysUserLoginLog;
import com.laolang.thresh.module.system.user.service.SysUserLoginLogService;
import eu.bitwalker.useragentutils.UserAgent;
import java.time.LocalDateTime;
import javax.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 系统登录日志常用业务方法.
 *
 * @author laolang
 * @version 0.1
 */
@RequiredArgsConstructor
@Service
public class SysUserLoginLogBusiness {

    private final HttpServletRequest request;
    private final SysUserLoginLogService sysUserLoginLogService;

    public void saveLoginLog(Long userId, OpType opType, OpSource opSource) {
        SysUserLoginLog loginLog = new SysUserLoginLog();
        loginLog.setUserId(userId);
        loginLog.setIp(ServletUtil.getIpAddr(request));
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
        loginLog.setClientType(userAgent.getOperatingSystem().getDeviceType().toString().toLowerCase());
        loginLog.setOs(userAgent.getOperatingSystem().getName());
        loginLog.setBrowser(userAgent.getBrowser().toString().toLowerCase());
        loginLog.setOpDatetime(LocalDateTime.now());
        loginLog.setOpType(opType.getCode());
        loginLog.setOpSource(opSource.getCode());
        sysUserLoginLogService.save(loginLog);
    }
}
